const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { body, validationResult } = require('express-validator');
const { authenticateToken, generateString, encryptPhone, decryptPhone, extractNumber, getNextId, logUserOperation } = require('../untils/untils');
const dayjs = require('dayjs')
const { cryptoHelper } = require('../config/global');
const fs = require('fs');
const path = require('path');

// 获取回访任务
router.get('/', authenticateToken, async (req, res) => {
    try {
        const { cust_id, emp_id  } = req.query;
        let sql = 'SELECT * FROM revisit_task WHERE 1=1';
        if (cust_id) {
            sql += ` AND cust_id = '${cust_id}'`;
        }
        if (emp_id) {
            sql += ` AND emp_id = '${emp_id}'`;
        }

        // 获取客户信息
        const [cust_info] = await db.execute(`SELECT cust_id, cust_name FROM customer`);
        // 获取员工表
        const [emp_info] = await db.execute(`SELECT emp_id, emp_name FROM employee`);

        let [result] = await db.execute(sql);
        result.forEach(item => {
            item.plan_date = dayjs(item.plan_date).format('YYYY-MM-DD HH:mm:ss');
            item.cust_name = cust_info.find(cust => cust.cust_id === item.cust_id)?.cust_name || '';
            item.emp_name = emp_info.find(emp => emp.emp_id === item.emp_id)?.emp_name || '';
        });
        await logUserOperation(req, '查询', '获取回访任务', '获取回访任务成功', '成功');
        res.json({
            success: true,
            message: '获取回访任务成功',
            data: result
        });
    } catch (error) {
        console.error('获取回访任务失败:', error);
        await logUserOperation(req, '查询', '获取回访任务', '获取回访任务失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取回访任务失败',
            error: error.message
        });
    }
});

// 新增回访任务
router.put('/add', authenticateToken, async (req, res) => {
    try {
        const { cust_id, consume_id, emp_id, plan_date, purpose } = req.body;
        const task_time = dayjs(plan_date).format('YYYY-MM-DD HH:mm:ss');
        const status = '待跟进';
        const task_id = await getNextId('RV', 'task_id', 'revisit_task', 5);
        const sql = `INSERT INTO revisit_task (task_id, cust_id, consume_id, emp_id, plan_date, purpose, status) VALUES (?, ?, ?, ?, ?, ?, ?)`;
        const params = [task_id, cust_id, consume_id, emp_id, task_time, purpose, status];
        await db.execute(sql, params);
        await logUserOperation(req, '添加', '新增回访任务', '新增回访任务成功', '成功');
        res.json({
            success: true,
            message: '新增回访任务成功',
            data: {
                task_id,
                cust_id,
                consume_id,
                emp_id,
                plan_date,
                purpose
            }
        });
    } catch (error) {
        console.error('新增回访任务失败:', error);
        await logUserOperation(req, '添加', '新增回访任务', '新增回访任务失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '新增回访任务失败',
            error: error.message
        });
    }
});

// 更新回访任务
router.post('/update', authenticateToken, async (req, res) => {
    try {
        const { task_id, cust_id, consume_id, emp_id, plan_date, purpose } = req.body;
        const task_time = dayjs(plan_date).format('YYYY-MM-DD HH:mm:ss');
        const sql = `UPDATE revisit_task SET cust_id = ?, consume_id = ?, emp_id = ?, plan_date = ?, purpose = ? WHERE task_id = ?`;
        const params = [cust_id, consume_id, emp_id, task_time, purpose, task_id];
        await db.execute(sql, params);
        await logUserOperation(req, '更新', '更新回访任务', '更新回访任务成功', '成功');
        res.json({
            success: true,
            message: '更新回访任务成功',
            data: {
                task_id,
                cust_id,
                consume_id,
                emp_id,
                plan_date,
                purpose
            }
        });
    } catch (error) {
        console.error('更新回访任务失败:', error);
        await logUserOperation(req, '更新', '更新回访任务', '更新回访任务失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '更新回访任务失败',
            error: error.message
        });
    }
});

// 删除回访任务
router.delete('/delete', authenticateToken, async (req, res) => {
    try {
        const { task_id } = req.query;
        const sql = `DELETE FROM revisit_task WHERE task_id = ?`;
        const params = [task_id];
        await db.execute(sql, params);
        await logUserOperation(req, '删除', '删除回访任务', '删除回访任务成功', '成功');
        res.json({
            success: true,
            message: '删除回访任务成功',
        });
    } catch (error) {
        console.error('删除回访任务失败:', error);
        await logUserOperation(req, '删除', '删除回访任务', '删除回访任务失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '删除回访任务失败',
            error: error.message
        });
    }
});

// 获取客户信息
router.get('/customer', authenticateToken, async (req, res) => {
    try {
        const sql = `SELECT cust_id as 'key', cust_name as 'name' FROM customer`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取客户信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取客户信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取客户信息失败',
            error: error.message
        });
    }
});

// 获取消费记录
router.get('/consumption', authenticateToken, async (req, res) => {
    try {
        const sql = `SELECT consume_id as 'key', consume_id as 'name' FROM consumption`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取消费记录成功',
            data: result
        });
    } catch (error) {
        console.error('获取消费记录失败:', error);
        res.status(500).json({
            success: false,
            message: '获取消费记录失败',
            error: error.message
        });
    }
});

// 获取员工信息
router.get('/employee', authenticateToken, async (req, res) => {
    try {
        const sql = `SELECT emp_id as 'key', emp_name as 'name' FROM employee`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取员工信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取员工信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取员工信息失败',
            error: error.message
        });
    }
});

// 获取查询项客户信息
router.get('/customer_query', authenticateToken, async (req, res) => {
    try {
        const sql = `SELECT DISTINCT customer.cust_id as 'key', customer.cust_name as 'name' FROM revisit_task JOIN customer ON revisit_task.cust_id = customer.cust_id`;
        const [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取查询项客户信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取查询项客户信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取查询项客户信息失败',
            error: error.message
        });
    }
});

// 获取查询跟进人员信息
router.get('/employee_query', authenticateToken, async (req, res) => {
    try {
        const sql = `SELECT DISTINCT employee.emp_id as 'key', employee.emp_name as 'name' FROM revisit_task JOIN employee ON revisit_task.emp_id = employee.emp_id`;
        const [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取查询跟进人员信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取查询跟进人员信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取查询跟进人员信息失败',
            error: error.message
        });
    }
});






module.exports = router;